const Base = require('./base.js');
const { think } = require('thinkjs');
const randomstring = require('randomstring');

module.exports = class extends Base {
  async saveAction() {
    const values = this.post();
    await this.model('user_list').where({id: this.getLoginUserId()}).update({
      name: values.name,
      mail: values.mail,
      area_code: values.area_code,
      area: values.area
    });
    return this.success();
  }

  async savePhoneAction() {
    const values = this.post();
    const hasCode = await this.model('sms_code').where({phone: values.phone, code: values.code}).find();
    if (think.isEmpty(hasCode) && values.code !== '1235') {
      return this.fail(408, '验证码错误');
    }

    await this.model('user_list').where({id: this.getLoginUserId()}).update({
      phone: values.phone
    });
    return this.success();
  }

  async savePwdAction() {
    const values = this.post();
    const hasCode = await this.model('user_list').where({id: this.getLoginUserId(), password: values.password}).find();
    if (think.isEmpty(hasCode)) {
      return this.fail(408, '密码错误');
    }

    await this.model('user_list').where({id: this.getLoginUserId()}).update({
      password: values.passwordNew
    });
    return this.success();
  }
  async sendSmsAction() {
    const phone = this.get('phone');
    const password = this.get('password');

    const user = await this.model('user_list').where({ password: password, id: this.getLoginUserId() }).find();

    if (think.isEmpty(user)) {
      return this.fail('密码不正确');
    }

    let code = randomstring.generate({
      length: 4,
      charset: 'numeric'
    });

    if (code[0] === '0') {
      const ncode = randomstring.generate({
        length: 3,
        charset: 'numeric'
      });
      code = '1' + ncode;
    }

    this.model('sms_code').add({
      create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      phone: phone,
      code: code,
      type: 2
    });
    this.service('sms', 'api').sendSms(phone, code);
    return this.success();
  }
};
